#!/bin/bash
# 相关配置信息
SERVER="datawin"
PASSWORD="datawin1q2w3e4r"
IP_ADDRESS="192.168.0.250"  # 添加服务器IP地址
COUNTRY="CN"
STATE="江苏省"
CITY="常州市"
ORGANIZATION="数赢云"
ORGANIZATIONAL_UNIT="Dev"
EMAIL="467723464@qq.com"

### 开始生成文件 ###
echo "开始生成文件"
cd /etc/docker || { echo "无法进入/etc/docker目录"; exit 1; }

# 1. 生成CA私钥(使用aes256加密)
openssl genrsa -aes256 -passout pass:${PASSWORD} -out ca-key.pem 2048

# 2. 生成CA证书
openssl req -new -x509 -passin "pass:${PASSWORD}" -days 3650 \
  -key ca-key.pem -sha256 -out ca.pem \
  -subj "/C=${COUNTRY}/ST=${STATE}/L=${CITY}/O=${ORGANIZATION}/OU=${ORGANIZATIONAL_UNIT}/CN=${SERVER}/emailAddress=${EMAIL}"

# 3. 生成服务器证书私钥
openssl genrsa -out server-key.pem 2048

# 4. 生成服务器证书请求文件
openssl req -subj "/CN=${SERVER}" -new -key server-key.pem -out server.csr

# 5. 创建包含IP SAN的扩展文件
cat > server-extfile.cnf <<EOF
subjectAltName = IP:${IP_ADDRESS}
extendedKeyUsage = serverAuth
EOF

# 6. 签发服务器证书(添加SAN扩展)
openssl x509 -req -days 3650 -in server.csr \
  -CA ca.pem -CAkey ca-key.pem -passin "pass:${PASSWORD}" \
  -CAcreateserial -out server-cert.pem \
  -extfile server-extfile.cnf

# 7. 生成客户端证书私钥
openssl genrsa -out key.pem 2048

# 8. 生成客户端证书请求文件
openssl req -subj '/CN=client' -new -key key.pem -out client.csr

# 9. 创建客户端证书扩展文件
echo "extendedKeyUsage = clientAuth" > client-extfile.cnf

# 10. 签发客户端证书
openssl x509 -req -days 3650 -in client.csr \
  -CA ca.pem -CAkey ca-key.pem -passin "pass:${PASSWORD}" \
  -CAcreateserial -out cert.pem \
  -extfile client-extfile.cnf

# 设置文件权限
chmod 0400 ca-key.pem key.pem server-key.pem
chmod 0444 ca.pem server-cert.pem cert.pem

# 清理临时文件
rm -f client.csr server.csr server-extfile.cnf client-extfile.cnf

echo "证书生成完成，包含IP SAN扩展"
echo "服务器IP: ${IP_ADDRESS} 已添加到证书"
